package com.wesley.lab.android;

import com.wesley.lab.android.utils.NotepadDBHelper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditActivity extends Activity {
	
	private EditText mTitleText;
	private EditText mBodyText;

	private NotepadDBHelper mDbHelper;
	
	private Long mRowId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_edit);
		
		setTitle(R.string.edit_note);
		
		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		
		Button confirmBtn = (Button) findViewById(R.id.confirm);
		
		mDbHelper = new NotepadDBHelper(this);
	    mDbHelper.open();
		
	    mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(NotepadDBHelper.KEY_ROWID);
	    if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(NotepadDBHelper.KEY_ROWID)
                                    : null;
        }

	    populateFields();
		
		confirmBtn.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        setResult(RESULT_OK);
		        finish();
		    }
		});
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(NotepadDBHelper.KEY_ROWID, mRowId);

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}
	
	private void saveState() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();

        if (mRowId == null) {
            long id = mDbHelper.createNote(title, body);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateNote(mRowId, title, body);
        }
    }
	
	private void populateFields() {
	    if (mRowId != null) {
			Cursor note = mDbHelper.fetchNote(mRowId);
			startManagingCursor(note);
			mTitleText.setText(note.getString(note
					.getColumnIndexOrThrow(NotepadDBHelper.KEY_TITLE)));
			mBodyText.setText(note.getString(note
					.getColumnIndexOrThrow(NotepadDBHelper.KEY_BODY)));
	    }
	}
}
